<template>
  <div class="contont">
    <!-- 左侧城市 -->
      <div class="mapList">
        <div class="box_area areaName" @click="getEart('china',0)">{{customerData.areaName}}</div>
        <ul class="area_ul">
          <li v-for="item in customerData.rows" @click="getEart(item.name,item.level)">{{item.name}}({{item.value}})</li>
        </ul>
        <div class="box_area customerType">客户类型分布</div>
        <ul class="areaType_ul">
          <li v-for="item in customerData.types">{{item.name}}({{item.value}})</li>
        </ul>
      </div>
      <div class="tabs">
        <ul>
          <li @click="getEart('china',0)">全国<i class="el-breadcrumb__separator el-icon-arrow-right"></i></li>
          <li v-show="two_name" @click="getEart(two_name,1)">{{two_name}}<i class="el-breadcrumb__separator el-icon-arrow-right"></i></li>
          <li v-show="three_name" @click="getEart(three_name,2)">{{three_name}}<i class="el-breadcrumb__separator el-icon-arrow-right"></i></li>
          <li v-show="four_name" @click="getEart(four_name,3)">{{four_name}}</li>
        </ul>
        <el-button type="primary" size="mini" @click="dialogVisible = true">高级查询</el-button>
        <el-button type="primary" size="mini" @click="recovery()">恢复地图</el-button>
        <!--<el-button type="primary" size="mini" @click="back()">返回上级</el-button>-->
      </div>
      <!-- 高级搜索 -->
      <el-dialog width="500px" title="高级查询" :visible.sync="dialogVisible">
        <el-form label-width="120px">
          <el-form-item label="销售区域:">
            <el-cascader 
                class="fill-width"
                clearable
                v-model="form.areaSn" 
                :options="areaList"
                :change-on-select="true"
              />
          </el-form-item>
          <el-form-item label="客户经理:">
            <el-select clearable class="fill-width" v-model="form.directorId" filterable placeholder="输入客户经理">
              <el-option
                v-for="item in teamList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型:">
            <el-select clearable class="fill-width" v-model="form.customerType" filterable placeholder="输入客户类型">
              <el-option
                v-for="item in customer_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="新增日期:">
            <el-date-picker
              clearable
              class="fill-width"
              v-model="form.queryDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <!-- <el-row :gutter="20">
          <el-col :span="6">
            销售区域:
          </el-col>
          <el-col :span="14">
            <avue-input type="tree" v-model="form.areaSn" :dic="areaList"/> -->
            <!-- <el-select v-model="form.areaSn" filterable placeholder="输入销售区域">
              <el-option
                v-for="item in arealist"
                :key="item.areaSn"
                :label="item.areaName"
                :value="item.areaSn">
              </el-option>
            </el-select> -->
          <!-- </el-col> -->
          <!--<el-col :span="3">-->
            <!--市场维度:-->
          <!--</el-col>-->
          <!--<el-col :span="7">-->
            <!--<el-select v-model="dimension" filterable placeholder="输入市场维度">-->
              <!--<el-option-->
                <!--v-for="item in options"-->
                <!--:key="item.value"-->
                <!--:label="item.label"-->
                <!--:value="item.value">-->
              <!--</el-option>-->
            <!--</el-select>-->
          <!--</el-col>-->
        <!-- </el-row>
        <el-row>
          <el-col :span="6">
            客户经理:
          </el-col>
          <el-col :span="14">
            <el-select v-model="form.directorId" filterable placeholder="输入客户经理">
              <el-option
                v-for="item in teamList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            客户类型:
          </el-col>
          <el-col :span="14">
            <el-select v-model="form.customerType" filterable placeholder="输入客户类型">
              <el-option key="1" label="经销商" value="1"></el-option>
              <el-option key="2" label="门店" value="2"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            创建时间:
          </el-col>
          <el-col :span="14">
            <el-date-picker
              v-model="form.createDate"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-col>
        </el-row>
        <el-row :gutter="20">

        </el-row> -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="batchCreate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 左右方向 -->
      <div class="box" v-show="is_eart">
        <div class="handle">
          <div class="t_l_r_b">
            <p><i class="el-icon-caret-top" @click="toUp"></i></p>
            <p><i class="el-icon-caret-left" @click="toLeft"></i></p>
            <p><i class="el-icon-caret-right" @click="toRight"></i></p>
            <p><i class="el-icon-caret-bottom" @click="toDown"></i></p>
          </div>
          <span><i class="el-icon-circle-plus-outline" style="margin-left: 5px;" @click="enlarge()"></i></span>
          <span><i class="el-icon-remove-outline" @click="narrow()"></i></span>
        </div>
        <div id="mapChart" class="chart"></div>
      </div>
      <div id="container" v-show="is_map" style="width:79%;"></div>
  </div>
</template>

<script>
  import cityMap from "@/util/china-main-city-map.js";
  import echarts from "echarts";
  import axios from "axios";
  import {fetchDictAsync} from '@/util/util';
  import { formatCascader } from '@/const/common/tool';
  import {
    customerMap,
  } from '@/api/crm/customerMap'
  //中国地图（第一级地图）的ID、Name、Json数据
  var chinaId = 100000;
  var chinaName = "china";
  var chinaJson = null;

  //记录父级ID、Name
  var mapStack = [];
  var parentId = null;
  var parentName = null;
  var mapJson = '';
  var name = 'china';
  var id = 100000;
  //Echarts地图全局变量，主要是在返回上级地图的方法中会用到
  var myChart = null;
  import AMap from 'AMap' // 引入高德地图
  import {
    fetchList,
  } from '@/api/crm/customer'
  import {
    areaTree,
  } from '@/api/crm/area'
  import {
    fetchList as teamList,
  } from '@/api/crm/marketemployee'
  export default {
    name: "chinaMap",
    props: {
      msg: String
    },
    data() {
      return {
        customerData:'',
        areaLevel:0,
        areaName:'全国',
        is_eart:true,
        is_map:false,
        two_name:'',
        three_name:'',
        four_name:'',
        dialogVisible:false,
        tableData:'',
        options:[{label:'重庆',value:'1'},{label:'成都',value:'2'},{label:'南昌',value:'3'}],
        dimension:'',
        areaList:[],
        teamList:[],
        form:{
          customerType:'',
          queryDate:'',
          areaSn:'',
          directorId:'',
        },
        customer_type: [],
      }
    },
    created(){
      fetchDictAsync('scm_customer_type', this.customer_type);
    },
    mounted: function() {
      this.fetchCtrList();
      this.getList();
    },
    methods: {
      batchCreate(){
        let areaName, level;
        if(this.four_name) {
          level = 3;
          areaName = this.four_name;
        }else if(this.three_name) {
          level = 2;
          areaName = this.three_name;
        }else if(this.two_name) {
          level = 1;
          areaName = this.two_name;
        }else {
          level = 0;
          areaName = '全国';
        }
        let query = JSON.parse(JSON.stringify(this.form));
        if(Array.isArray(query.areaSn) && query.areaSn.length > 0) query.areaSn = query.areaSn[query.areaSn.length -1];
        query = Object.assign({level, areaName}, query);
        customerMap(query).then(response => {
          if (response.data.code == 0) {
            this.customerData = response.data.data;
            this.mapChart("mapChart",response.data.data);
          } else {
            this.$message.warning('暂无客户信息');
            this.customerData = '';
          }
          this.dialogVisible = false;
        })
      },
      //查询客户列表
      getList(params={}) {
        params.pageSize = 1000
        params.pageNo = 1
        fetchList(params).then(response => {
          if (response.data.code == 0) {
            console.log(response);
          } else {
            this.$message.warning(response.msg);
          }
        })
        areaTree(Object.assign({
          current: 1,
          size: 1000
        }, params, this.searchForm)).then(response => {
          // this.arealist = response.data.data.records
          this.areaList = formatCascader(response.data.data, 'areaName', 'areaSn');
        })
        teamList(Object.assign({
          current: 1,
          size: 1000
        }, params, this.searchForm)).then(response => {
          this.teamList = response.data.data.records
        })
      },
      //获取信息
      fetchCtrList(name) {
        let params = {};
        params.level = this.areaLevel
        params.areaName = this.areaName
        if(name){
          params.areaName = name;
        }
        customerMap(params).then(response => {
          if (response.data.code == 0) {
            this.customerData = response.data.data;
            this.mapChart("mapChart",response.data.data);
          } else {
            this.$message.warning('暂无客户信息');
            this.customerData = '';
          }
        })
      },
      //获取客户信息
      /**
       * 返回上一级地图
       */
      back() {
        if(this.is_map == true){
          this.is_eart = true;
          this.is_map = false;
        }
        if (mapStack.length != 0) {
          //如果有上级目录则执行
          var map = mapStack.pop();
          axios
            .get("/json/map/" + map.mapId + ".json", {})
            .then(response => {
              mapJson = response.data;
              registerAndsetOption(
                myChart,
                map.mapId,
                map.mapName,
                mapJson,
                false,
                this.customerData
              );
              //返回上一级后，父级的ID、Name随之改变
              parentId = map.mapId;
              parentName = map.mapName;
              this.areaLevel--;
              name =  map.name;
              id =  map.mapId;
            });
        }
      },
      //点击菜单去地图
      getEart(name,level){
        if(level == 4){
          return false;
        }
        this.is_eart = true;
        this.is_map = false;
        var cityId = cityMap[name];
        let params = {};
        params.shopId = 9
        params.pmId = 9
        params.uId = 9
        params.level =  level
        params.areaName = name;
          if(params.areaName === '重庆市' || params.areaName === '北京市' || params.areaName === '天津市' || params.areaName === '上海市'|| params.areaName === '香港特别行政区'|| params.areaName === '澳门特别行政区') {
              params.level = 2;
          }
        if(level == 0){
          cityId = 100000;
          this.two_name = '';
          this.three_name = '';
          this.four_name = '';
          this.areaLevel = 0;
        }
        if(level == 1){
          this.three_name = '';
          this.two_name = name;
          this.areaLevel = 1;
        }
        if(level == 2){
          this.three_name = name;
          this.four_name = '';
          this.areaLevel = 2;
        }
        if(level == 3){
          this.four_name = name;
          this.areaLevel = 3;
        }

        customerMap(params).then(response => {
          if (response.data.code === 0) {
            this.customerData = response.data.data;
            if(cityId){
              axios
                .get("/json/map/" + cityId + ".json", {})
                .then(res => {
                  mapJson = res.data;
                  registerAndsetOption(
                    myChart,
                    cityId,
                    name,
                    mapJson,
                    true,
                    response.data.data
                  );
                });
              name = name;
              id = cityId;
            }else{
              this.is_eart = false;
              this.is_map = true;
              init(response.data.data);
            }
          } else {
            this.$message.warning('暂无客户信息');
          }
        })
      },
      //地图操作
      //放大
      enlarge(){
        enlarge(this.customerData)
      },
      //缩小
      narrow(){
        narrow(this.customerData)
      },
      //向上
      toUp(){
        toUp(this.customerData)
      },
      //向左
      toLeft(){
        toLeft(this.customerData)
      },
      //向右
      toRight(){
        toRight(this.customerData)
      },
      //向下
      toDown(){
        toDown(this.customerData)
      },
      //恢复原状
      recovery(){
        this.getEart('china',0);
        // recovery(this.customerData)
      },
      /**
       * Echarts地图
       */

      mapChart(divid,customerData) {
        axios.get("/json/map/" + chinaId + ".json", {}).then(response => {
          mapJson = response.data;
          chinaJson = mapJson;
          myChart = echarts.init(document.getElementById(divid));
          registerAndsetOption(myChart, chinaId, chinaName, mapJson, false,customerData);
          parentId = chinaId;
          parentName = "china";
          var that = this;
          myChart.on("click", function(param) {
              that.areaLevel++;
              var cityId = cityMap[param.name];
              let params = {};
              params.shopId = 9
              params.pmId = 9
              params.uId = 9
              params.level =  that.areaLevel
              params.areaName = param.name;
              if(param.name === '重庆市' || param.name === '北京市' || param.name === '天津市' || param.name === '上海市'|| param.name === '香港特别行政区'|| param.name === '澳门特别行政区') {
                  params.level = 2;
                  that.areaLevel = 2;
              }
              if(that.areaLevel === 1){
                that.two_name = param.name;
              }
              if(that.areaLevel === 2){
                that.three_name = param.name;
              }
              if(that.areaLevel === 3){
                that.four_name = param.name;
              }
              customerMap(params).then(response => {
                if (response.data.code === 0) {
                  that.customerData = response.data.data;
                  if(cityId){
                    axios
                      .get("/json/map/" + cityId + ".json", {})
                      .then(res => {
                        mapJson = res.data;
                        registerAndsetOption(
                          myChart,
                          cityId,
                          param.name,
                          mapJson,
                          true,
                          response.data.data
                        );
                      });
                    name = param.name;
                    id = cityId;
                  }else{
                    that.is_eart = false;
                    that.is_map = true;
                    init(response.data.data);
                  }
                } else {
                  that.$message.warning('暂无客户信息');
                }
              })
              //代表有下级地图
          });
        });
      }
    }
  };
  //地图
  function init (customerData) {
    var map = new AMap.Map('container',{resizeEnable: true,zoom:10});
    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
    AMap.plugin([
      'AMap.ToolBar',
      'AMap.Scale',
    ], function(){
      // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
      map.addControl(new AMap.ToolBar());

      // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
      map.addControl(new AMap.Scale());

    });
    console.log(customerData);
    let provinces = customerData.details;
    var markers = []; //province见Demo引用的JS文件
    for (var i = 0; i < provinces.length; i += 1) {
      var marker;
      var content= "<div class = 'provinces'>"+ provinces[i].name +"</div>"; //信息
      var info = '';
      info += "<div class='input-card content-window-card'><div><img src='https://webapi.amap.com/images/autonavi.png'/></div>";
      info += "<div><h4 style='padding:7px 0 0;'>"+ provinces[i].name +"</h4>"
      info += "<p style='padding:7px 0 0;font-size: 12px;' class='input-item'>电话："+ provinces[i].tel +"</p>"
      info += "<p style='padding:7px 0 0;font-size: 12px;' class='input-item'>地址 :"+ provinces[i].address +"</p></div></div>"
      marker = new AMap.Marker({
        title: provinces[i].name,
        position: provinces[i].center.split(','),
        map: map
      });
      marker.content = info;
      marker.on('click', markerClick);
      marker.emit('click', {target: marker});
      markers.push(marker);
    }
    //点击地图icon信息显示隐藏
    function markerClick(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(map, e.target.getPosition());
    }
    map.setFitView();
  }

  /**
   *
   * @param {*} myChart
   * @param {*} id        省市县Id
   * @param {*} name      省市县名称
   * @param {*} mapJson   地图Json数据
   * @param {*} flag      是否往mapStack里添加parentId，parentName
   */
  var zoom = 1;
  var left = 260;
  var top = 110;
  function enlarge(customerData) {
    if(zoom > 5){
      return false
    }
    zoom++;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function narrow(customerData) {
    if(zoom == 1){
      return false
    }
    zoom--;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function toUp(customerData) {
    if(top == 10){
      return false
    }
    top = top - 20;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function toDown(customerData) {
    if(top == 400){
      return false
    }
    top = top + 20;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function toLeft(customerData) {
    if(left == 0){
      return false
    }
    left = left - 20;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function toRight(customerData) {
    if(left == 500){
      return false
    }
    left = left + 20;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function recovery(customerData) {
    console.log(customerData);
    zoom = 1;
    left = 260;
    top = 110;
    registerAndsetOption(myChart,id,name,mapJson,true,customerData);
  }
  function registerAndsetOption(myChart, id, name, mapJson, flag,customerData) {
        var mapData = [];
        document.getElementsByClassName("areaName").innerHTML = name;
        for (var i = 0; i < mapJson.features.length; i++) {
          mapData.push({
            name: mapJson.features[i].properties.name,
            value:0
            //id:mapJson.features[i].id
          });
        }
        customerData.rows.forEach((item)=>{
          mapData.forEach((child)=>{
            if(item.name == child.name){
              child.value = item.value
            }
          })
        })
        echarts.registerMap(name, mapJson);
        myChart.setOption({
          title: {
              textStyle: {
                  color: '#999999'
              }
          },
          tooltip : {
            trigger: 'item'
          },
          visualMap: {
            pieces: [
              {min: 100},
              {min: 50, max: 100},
              {min: 10, max: 50},
              {min: 1, max: 10},
              {max: 1},
            ],
            color: ['#d94e5d','#eac736','#dddddd'],
            textStyle: {
              color: '#888'
            }
          },
          series: [
            {
              type: 'map',
              map: name,
              name: '客户数量',
              label: {
                normal: {
                  show: true
                },
                emphasis: {
                  show: true
                }
              },
              zoom:zoom,
              left:left,
              top:top,
              itemStyle: {
                normal: {
                  areaColor: "#eee",
                  borderColor: "#ccc",
                  borderWidth: 1
                }
              },
              data: mapData
            }
          ]
        });
    if (flag) {
      //往mapStack里添加parentId，parentName,返回上一级使用
      mapStack.push({
        mapId: parentId,
        mapName: parentName
      });
      parentId = id;
      parentName = name;
    }
  }
  window.onresize = function(){
    myChart.resize();
  }
</script>

<style>

</style>

<style scoped>
  .contont{
    width: auto;
    padding: 0;
    background-color: #fff;
    border-radius: 6px;
    margin:0 15px 0;
    position: relative;
    overflow: hidden;
    height: 100%;
  }



  .box_area{
    background-color: #f7f7f7;
    border: 1px solid #eee;
    padding: 10px;
  }
  .mapList{
    width: 20%;
    min-width: 240px;
    height: calc(100vh - 180px);
    float: left;
    border-right: 1px solid #eee;
  }
  .mapList li{
    border-bottom: 1px solid #eee;
    padding: 10px;
    cursor: pointer;
  }
  .box {
    width: 79.8%;
    height: calc(100% - 45px);
    background-color: #fff;
    float: right;
    position: relative;
  }
  .tabs{
    position: absolute;
    top: 0;
    right: 0;
    width: 80%;
    padding: 8px 0;
    margin-left: 20px;
    z-index: 15;
    background-color: #fff;
    border-bottom: 1px solid #ddd;
    font-size: 14px;
    line-height: 28px;
  }
  .tabs button{
    float: right;
    margin-right: 10px;
  }
  .tabs li{
    float: left;
    padding-left: 10px;
    color: #666;
    cursor: pointer;
  }
  #container{
    position: absolute;
    top: 45px;
    right: 0;
    width: 80%;
    height: calc(100% - 45px);
    z-index: 8;
  }
  .chart {
    position: relative;
    height: 100%;
    top: 0;
    z-index: 9;
  }
  .box .handle{
    position: absolute;
    top: 50px;
    left: 0;
    padding: 10px;
    z-index: 20;
  }
  .box .handle i{
    font-size: 36px;
    margin: 0 10px;
  }
  .t_l_r_b{
    border: 1px solid #ddd;
    border-radius: 100%;
    background-color: #f8f8f8;
    width: 100px;
    height: 100px;
    margin-bottom: 15px;
  }
  .t_l_r_b p{
    text-align: center;
  }
  .box .handle .t_l_r_b p i{
    margin: 0;
    font-size: 32px;
  }
  .t_l_r_b p:nth-child(2){
    float: left;
    width: 50%;
    text-align: left;
  }
  .t_l_r_b p:nth-child(3){
    float: right;
    width: 50%;
    text-align: right;
  }
</style>
